package com.webchat.admin.filter;

import com.webchat.admin.service.UserSessionService;
import com.webchat.common.config.properties.OauthProperties;
import com.webchat.common.constants.CookieConstants;
import com.webchat.common.enums.BaseErrCodeEnum;
import com.webchat.common.helper.SessionHelper;
import com.webchat.common.util.JsonUtil;
import com.webchat.rmi.sso.OauthServiceClient;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 程序员七七
 * @Date: 16.11.21 11:26 下午
 */
@Slf4j
@Order(-6)
@WebFilter(filterName = "oauthFilter", urlPatterns = {"/*"})
@Component
public class OauthFilter implements Filter {

    @Autowired
    private OauthProperties oauthProperties;

    @Autowired
    private OauthServiceClient oauthServiceClient;

    @Autowired
    private UserSessionService userSessionService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 取集中session服务判断是否已经登录，如果已经登录则直接进入后续方法。
        String oauthCode = request.getHeader("oauth-code");
        String userId = userSessionService.getUserIdByRequest(request);
        if (StringUtils.isNotBlank(userId)) {
            // 已经登录
            SessionHelper.setUserId(userId);
            try {
                filterChain.doFilter(request, response);
            } finally {
                SessionHelper.clear();
            }
            return;
        }
        if (StringUtils.isNotBlank(oauthCode)) {
            userId = oauthServiceClient.getUserIdByOauthCode(oauthCode).getData();
            if (StringUtils.isNotBlank(userId)) {
                userSessionService.createUserLoginSession(response, userId);
                SessionHelper.setUserId(userId);
                try {
                    filterChain.doFilter(request, response);
                } finally {
                    SessionHelper.clear();
                }
                return;
            }
        }
        /**
         * 302 重定向到统一登录页面
         */
        this.unLogin(request, response);
    }

    private void unLogin(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> responseMap = new HashMap<>();
        response.setCharacterEncoding("UTF-8"); // 设置字符编码为 UTF-8
        response.setContentType("application/json;charset=UTF-8"); // 设置内容类型和字符编码
        responseMap.put("code", BaseErrCodeEnum.UN_LOGIN.getCode());
        responseMap.put("message", BaseErrCodeEnum.UN_LOGIN.getMessage());
        responseMap.put("redirect_url", getRedirectUrl(request));
        try {
            response.getWriter().println(JsonUtil.toJsonString(responseMap));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String getRedirectUrl(HttpServletRequest request) {
        String serverUrl = oauthProperties.getServerUrl();
        String originUrl = request.getHeader("origin-url");
        return String.format(serverUrl, URLEncoder.encode(originUrl));
    }

    @Override
    public void destroy() {

    }
}
